const { orderBy } = require('lodash');
const { staff_collection, obdLongLat_collection } = require('../config');
const { db } = require('../config');
const { command } = require('../config');
const _ = command;
const fs = require('fs'); // 引入fs模块用来读取文件

var staffName, staffId;

// 统计装维看管的镇或街道的数量
exports.main = async (event, context) => {
    try {
        // 读取员工信息的JSON文件
        const staffFilePath = `${__dirname}/staff.json`; // JSON文件路径
        const staffData = await new Promise((resolve, reject) => {
            fs.readFile(staffFilePath, 'utf8', (err, data) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(JSON.parse(data));
                }
            });
        });

        // 过滤出符合条件的员工信息
        const staffInfos = staffData.filter(staff => staff.status !== '离职' && staff.position === '全职装维');
        var i = 1;
        // 遍历每个员工的信息
        for (const staff of staffInfos) {
            staffName = staff.name;
            staffId = staff._id;
            if (staff.obdLongLat) {
                const points = staff.obdLongLat;
                console.log("序号：", i, staff.name, staff._id, '共：' + staff.obdLongLat.length + '个OBD');
                try {
                    const townOrStreeInfo = await getTownOrStreesFromJSON(points);
                    if (townOrStreeInfo) {
                        console.log(townOrStreeInfo.townOrStrees, townOrStreeInfo.townOrStreeCount, '镇/街道，数量');
                        // 更新数据库
                        var upYes = await db.collection(staff_collection).where({ _id: staff._id }).limit(1).update({
                            obdTown: [...townOrStreeInfo.townOrStrees],
                            obdTownCount: townOrStreeInfo.townOrStreeCount
                        });
                        console.log("upYes",upYes)
                    } else {
                        var upNo = await db.collection(staff_collection).where({ _id: staff._id }).limit(1).update({
                            obdTown: _.remove(),
                            obdTownCount: _.remove()
                        });
                        console.log("upNo",upNo)
                        console.log('无负责obd');
                    }
                } catch (error) {
                    return { body: JSON.stringify({ error: error.message }) };
                }
            } else {
                var upNo = await db.collection(staff_collection).where({ _id: staff._id }).limit(1).update({
                    obdTown: _.remove(),
                    obdTownCount: _.remove()
                });
                console.log("upNo",upNo)
                console.log("员工", staff.name, "没有有效的obdLongLat信息");
            }
            i++;
        }

        return "处理结束";
    } catch (error) {
        console.error(`读取员工信息时发生错误:`, error.message);
    }
};

// 从JSON文件中获取镇或街道信息
async function getTownOrStreesFromJSON(points) {
    if (points.length === 0) {
        return false;
    }

    // 读取镇或街道信息的JSON文件
    const townFilePath = `${__dirname}/town.json`; // JSON文件路径
    const townData = await new Promise((resolve, reject) => {
        fs.readFile(townFilePath, 'utf8', (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(JSON.parse(data));
            }
        });
    });

    // 将JSON数据转换成对象数组
    const townList = Array.isArray(townData) ? townData : [townData];

    const results = points.map(point => {
        const lat = String(point.lat);
        const lng = String(point.lng);
        const matchedTown = townList.find(entry => entry.lng === lng && entry.lat === lat);
        return matchedTown ? matchedTown.townStreet : null;
    });

    const uniqueTownOrStrees = countUniqueTownOrStrees(results);
    return uniqueTownOrStrees;
}

// 计算跨越的区划数量
function countUniqueTownOrStrees(townOrStrees) {
    const uniqueTownOrStrees = new Set(townOrStrees.filter(Boolean));
    console.log("跨越的镇或街区划数量:", uniqueTownOrStrees.size, staffName, staffId);
    return { townOrStrees: Array.from(uniqueTownOrStrees), townOrStreeCount: uniqueTownOrStrees.size };
}